# Script que obtem a data e hora do dynboot.

# Este script utiliza o web service do dynboot para obter a hora local do servidor. 
# O arquivo netclock.nsh é gerado com data e hora do servidor dynboot e se invocado 
# no shell uefi, irá configurar o relógio.
# As URLs dos web services estão no arquivo URLs.py.

# Caso a execução seja feita com sucesso, o exit code será 0

import urllib2
import sys
import string
import os
import time
import io
import email.utils as eut

sys.path.append(os.path.dirname(__file__))
from URLs import *

if (len(sys.argv) != 2):
	print "DynbootClock.py - Usage: DynbootClock.py PastaDestinoNetClock.nsh"
	sys.exit(-1)
	
def GetXmlTagText(XML, TAG):
	startTag = XML.find('<'+TAG+'>')
	if (startTag > 0) :
		startTag += len(TAG)+2
		endTag = XML.find('</'+TAG+'>')
		if (endTag > 0) :
			return XML[startTag:endTag].strip()
	return ''
	
# Call the dynboot horaRequest WebService to get the server date and time.
# Return a dictionary with year, month, day, hour, minute and second items or null if failed
def DynbootGetDateTime():
	calendar = {}
	site = URLs[os.environ["LOCATION"]]['dynBoot']
	requestXml = """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ws="ws:dynboot">\r\n
	   <soapenv:Header/>\r\n
	   <soapenv:Body>\r\n
		  <ws:horaRequest>\r\n
			 <pattern>0</pattern>\r\n
		  </ws:horaRequest>\r\n
	   </soapenv:Body>\r\n
	</soapenv:Envelope>"""

	headers = {
		 'Content-Type': 'text/xml; charset=utf-8',
		 'Content-Length': len(requestXml),
		 'SOAPAction': site
	}

	resultXml = ""
	try:
		req = urllib2.Request(site, requestXml, headers)
		response = urllib2.urlopen(req)
		resultXml = response.read()
		response.close()
		
		if (resultXml.find('<status>S</status>') > 0):
			datetimeString = GetXmlTagText(resultXml, 'hora')
			print datetimeString
			if (len(datetimeString) == 19):
				calendar['day'] = int(datetimeString[0:2])
				calendar['month'] = int(datetimeString[3:5])
				calendar['year'] = int(datetimeString[6:10])
				calendar['hour'] = int(datetimeString[11:13])
				calendar['minute'] = int(datetimeString[14:16])
				calendar['second'] = int(datetimeString[17:19])
		else:
			serverDate = response.headers["Date"]
			date = time.mktime(eut.parsedate(serverDate.strip())) - 3 * 60 * 60
			tm = time.localtime(date)
			print tm
			calendar['day'] = tm.tm_mday
			calendar['month'] = tm.tm_mon
			calendar['year'] = tm.tm_year
			calendar['hour'] = tm.tm_hour
			calendar['minute'] = tm.tm_min
			calendar['second'] = tm.tm_sec
	except:
		return {}
	return calendar

try:
	print "DynbootClock.py - Obtendo horario do servidor dynboot."
	calendar = DynbootGetDateTime()
	if (not calendar):
		print "DynbootClock.py - Erro obtendo relogio do servico dynboot."
		sys.exit(-1)
	with open(sys.argv[1], 'w') as f:
		f.write('date %02d/%02d/%04d\r\n' % (calendar['month'], calendar['day'], calendar['year']))
		f.write('time %02d:%02d:%02d' % (calendar['hour'], calendar['minute'], calendar['second']))

except Exception, e:
	print "DynbootClock.py - Exception obtendo relogio do servico dynboot."
	print e
	sys.exit(-1)